package com.situ.ymall.service.impl;

import com.situ.ymall.entity.Goods;
import com.situ.ymall.entity.Shopcart;
import com.situ.ymall.mapper.GoodsMapper;
import com.situ.ymall.mapper.ShopcartMapper;
import com.situ.ymall.service.ShopCartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class ShopCartServiceImpl implements ShopCartService {

    @Autowired
    private ShopcartMapper shopcartMapper;
    @Autowired
    private GoodsMapper goodsMapper;

    @Override
    public int add(Shopcart cart) {

        Shopcart selectCart = shopcartMapper.select(cart);
        if (selectCart != null){
            //在原来的基础上更新
            selectCart.setCount(selectCart.getCount() + 1);
            //更新到数据库中
            return shopcartMapper.updateByPrimaryKey(selectCart);
        }else {
            int insert = shopcartMapper.insert(cart);
            return insert;
        }
    }

    @Override
    @Transactional
    public List getByUserId(Integer userId) {
        List<Shopcart> shopcarts = shopcartMapper.selectByUserId(userId);
        for (Shopcart shopcart : shopcarts){
            if (shopcart.getCount() > shopcart.getGoods().getCount()){
                shopcart.setCount(shopcart.getGoods().getCount());
                shopcartMapper.updateByPrimaryKey(shopcart);
            }
        }
        return shopcarts;
    }

    @Override
    public Shopcart update(Shopcart shopcart) {
        //验证一下商品的数量 获取商品信息
        Shopcart selectCart = shopcartMapper.selectByPrimaryKey(shopcart.getId());
        //查询商品的信息
        Goods goods = goodsMapper.selectByPrimaryKey(selectCart.getGoodsId());

        if (goods.getCount() < shopcart.getCount()){
            selectCart.setCount(goods.getCount());
            shopcartMapper.updateByPrimaryKey(selectCart);
        }else {
            shopcartMapper.updateByPrimaryKey(shopcart);
        }
        return shopcartMapper.selectByPrimaryKey(shopcart.getId());
    }

    @Override
    public int delete(Integer id) {

        return shopcartMapper.deleteByPrimaryKey(id);
    }
}
